package com.shen.thread.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//分析性能问题
public class Test4 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        test1();
        test2();
        test3();
    }

    //普通方式调用
    public static void test1() {
        User user = new User();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            user.getName();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms");
    }

    //反射方式调用
    public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class cl = user.getClass();
        Method getName = cl.getDeclaredMethod("getName", null);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            getName.invoke(user, null);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms");
    }

    //反射方式调用（关闭检测）
    public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class cl = user.getClass();
        Method getName = cl.getDeclaredMethod("getName", null);
        getName.setAccessible(true);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            getName.invoke(user, null);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms");
    }
}
